package com.chaihu.common;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.nio.charset.Charset;

@SpringBootApplication(scanBasePackages = {
        "com.chaihu.service",
        "com.chaihu.core",
        "com.chaihu.common",
        "com.chaihu.config",
        "com.chaihu.db"
})
@EnableDiscoveryClient
@EnableSwagger2
@EnableFeignClients(basePackages = {
        "com.chaihu.intf.common"})
public class CommonServiceApplicationStart {

    /**
     * 实例化RestTemplate，通过@LoadBalanced注解开启均衡负载能力.
     *
     * @return restTemplate
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        m.setWriteAcceptCharset(false);
        RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(RestTemplate.class);
        return restTemplate;
    }

    @Bean(value = "defaultApi")
    public Docket defaultApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //.title("swagger-bootstrap-ui-demo RESTful APIs")
                        .description("柴胡博客-通用服务")
                        .termsOfServiceUrl("https://www.chaihu.cc")
                        .version("1.0.0")
                        .build())
                //分组名称
                .groupName("通用服务")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.chaihu.common"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    public static void main(String[] args) {
//        ApplicationContext context = SpringApplication.run(CommonServiceApplicationStart.class, args);

        SpringApplication.run(CommonServiceApplicationStart.class, args);
    }
}
